home *** CD-ROM | disk | FTP | other *** search
- Path: ix.netcom.com!news
- From: miker3@ix.netcom.com (Mike Rubenstein)
- Newsgroups: comp.lang.c++
- Subject: Re: String operator+ and memory leakage.
- Date: Fri, 19 Apr 1996 16:02:18 GMT
- Organization: Netcom
- Message-ID: <3177b7d5.149465039@nntp.ix.netcom.com>
- References: <4l5foo$fen@utopia.hacktic.nl>
- NNTP-Posting-Host: ix-dc14-19.ix.netcom.com
- X-NETCOM-Date: Fri Apr 19 11:05:51 AM CDT 1996
- X-Newsreader: Forte Agent .99d/32.182
-
- Mike Tavares <MIKET@cdynamics.com> wrote:
-
- > I have an implementation (not mine) of the String class that is leaking
- > memory
- > during the + operator code. The code follows:
- >
- > class String
- > {
- > public:
- >
- > // Constructors/destructors
- > String();
- > String( char* new_string);
- > String( String& new_string);
- >
- > ~String()
- > {
- > delete character_array;
- > }
- >
- > String& operator+( String& a_string );
- > String& operator=( String& a_string );
- > operator char* () { return character_array; }
- >
- > private:
- >
- > char* character_array;
- > int string_length;
- > };
- >
- > String&
- > String::operator+( String& a_string )
- > {
- > int total_size = string_length + strlen( a_string ) + 1;
- > char* temp_array = new char[total_size];
- > char* char_array = a_string;
- >
- > strcpy( temp_array, character_array );
- > strcat( temp_array, char_array );
- >
- > String* new_string = new String( temp_array );
- > delete [] temp_array;
- > return *new_string;
- > }
- >
- > String&
- > String::operator=( String& a_string )
- > {
- > char* new_char_array = a_string;
- > delete [] character_array;
- > character_array = new char[strlen( new_char_array ) + 1];
- > strcpy( character_array, new_char_array );
- > string_length = strlen( character_array );
- > return *this;
- > }
- >
- > My usage is:
- >
- > destString = string1 + string2 + string3...;
- >
- >
- > The problem is, when new_string is created and returned through a
- > reference, no one ever deletes it.
- >
- > If I change new_string to be an automatic variable I get an error from
- > the compiler about trying to pass a reference to a item that is out of
- > scope.
- >
- > If I change the method to work in this I mutate one of my addends. There
- > has to be a way of implementing this without memory leakage! HELP!
-
- Don't return a reference. Something like
-
- String&
- String::operator+( String& a_string )
- {
- int total_size = string_length + strlen( a_string ) + 1;
- char* temp_array = new char[total_size];
- char* char_array = a_string;
-
- strcpy( temp_array, character_array );
- strcat( temp_array, char_array );
-
- String new_string(temp_array);
- delete [] temp_array;
- return new_string;
- }
-
-
- Michael M Rubenstein
-